import request from '../utils/request';
import qs from 'qs';

const baseUrl = '/cpi/';
const baseSysUrl = '/bpi/';

const getToken = () => {
    return window.localStorage.getItem('token');
};

const getReqeust = (query, url) => {
    return new Promise((resolve, reject) => {
        request({
            url: baseUrl + url,
            method: 'get',
            params: querySimple(query),
            headers: {
                'Content-Type': 'application/json; charset=utf-8',
                'Authorization': 'Basic c3dvcmQ6c3dvcmRfc2VjcmV0',
                'blade-auth': getAuthHeader()
            }
        }).then(res => {
            if (res.code === 200 || res.success) {
                resolve(res.data);
            }
            else if (res.code === 401 || (res.code === 500 && res.msg === 'token错误或过期')) {
                localStorage.removeItem('ms_username');
                window.location.href = '/#/login';
            }
            else {
                rejectHelper(res, reject);
            }
        }).catch(err => {
            rejectHelper(err, reject);
        });
    });
};
const getRequestFile = (query, url) => {
    return new Promise((resolve, reject) => {
        var strUrl = baseUrl + url + '?';
        var i = 0;
        for (var key in query) {
            if (i > 0) {
                strUrl = strUrl + '&';
            }
            strUrl = strUrl + key + '=' + query[key];
            i++;
        }
        resolve(strUrl);
    });
};
const getStreamReqeust = (query, url) => {
    return request({
        url: baseUrl + url,
        method: 'get',
        params: query,
        responseType: 'blob'});
};
const postStreamReqeust = (query, url) => {
    return request({
        url: baseUrl + url,
        method: 'post',
        data: json2FormData(query),
        responseType: 'blob'});
};
const postReqeust = (query, url, isJson) => {
    return new Promise((resolve, reject) => {
        request({
            url: baseUrl + url,
            method: 'post',
            data: isJson ? query : json2FormData(query),
            headers: {
                'Content-Type': 'application/json; charset=utf-8',
                'Authorization': 'Basic c3dvcmQ6c3dvcmRfc2VjcmV0',
                'blade-auth': getAuthHeader()
            }
        }).then(res => {
            if (res.code === 200 || res.success) {
                resolve(res.data);
            }
            else if (res.code === 401 || (res.code === 500 && res.msg === 'token错误或过期')) {
                localStorage.removeItem('ms_username');
                window.location.href = '/#/login';
            }
            else {
                rejectHelper(res, reject);
            }
        }).catch(err => {
            rejectHelper(err, reject);
        });
    });
};
const getReqeustSys = (query, url) => {
    return request({
        url: baseSysUrl + url,
        method: 'get',
        params: query
    });
};
const postReqeustSys = (query, url) => {
    return new Promise((resolve, reject) => {
        request({
            url: baseSysUrl + url,
            method: 'post',
            data: json2FormData(query),
            headers: {
                'Content-Type': 'application/json; charset=utf-8'
            }
        }).then(res => {
            if (res.status === 200) {
                resolve(res);
            }
            else if (res.status === 500 && res.msg === 'token错误或过期') {
                localStorage.removeItem('ms_username');
                window.location.href = '/#/login';
            }
            else {
                rejectHelper(err, reject);
            }
        }).catch(err => {
            rejectHelper(err, reject);
        });
    });
};

function rejectHelper(res, reject) {
    if (typeof(res) === 'string') {
        if (res.indexOf('请求未授权') > -1) {
            localStorage.removeItem('ms_username');
            window.location.href = '/#/login';
        }
        else {
            reject(res);
        }
    }
    else if (res.message) {
        reject(res.message, res);
    }
    else if (res.msg) {
        reject(res.msg, res);
    }
    else {
        reject('服务器错误');
    }
}

function querySimple(query) {
    var params = Object.assign({}, query);
    for (var key in params) {
        if (params[key] === '') {
            delete params[key];
        }
    }
    return params;
}

function queryWithToken(query) {
    var queryNew = {'token': getToken()}
    for (var key in query) {
        var item = query[key];
        queryNew[key] = item;
    }
    return queryNew;
}

function getAuthHeader() {
    var token = window.localStorage.getItem('token');
    token = token && token.indexOf('{') > -1 ? JSON.parse(token) : {};
    var auth = token.accessToken ? token.tokenType + ' ' + token.accessToken : '';
    return auth;
}

function queryWithSearch(query) {
    var queryNew = {'kw': '', 'page': 1, 'size': 20}
    for (var key in query) {
        var item = query[key];
        queryNew[key] = item;
    }
    return queryNew;
}

function json2FormData(dictionary) {
    var formdata = new FormData()
    for (var key in dictionary) {
        var item = dictionary[key];
        if ((item instanceof Array) && item.length > 0 && item[0] instanceof File) {
            for (var index in item) {
                formdata.append(key, item[index]);
            }
        }
        else {
            formdata.append(key, item);
        }
    }
    return formdata
}

const base = {
    getToken,
    getReqeust,
    getRequestFile,
    postReqeust,
    queryWithToken,
    json2FormData,
    queryWithSearch,
    getStreamReqeust,
    postStreamReqeust,
    getReqeustSys,
    postReqeustSys
};

export default base;
